import { adminLogin, logout, getInfo,cusRoleList } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,constantRoutes } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo:{}
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERINFO: (state,data) => {
    state.userInfo = data
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      adminLogin({ account: username.trim(), pwd: password ,platform:2}).then(async response => {
        const res = response.rows[0]
        const {rows} = await cusRoleList({ pageNum: 1,pageSize: 10000, platform:''})
        const result = rows.find(item => item.id == res.roles);
        if(result){
          const rolesList = result.menuIds.split(',')
          constantRoutes.forEach(item => {
            let allChildrenHiddenTrue = true;
            if (item.children && item.children.length > 0) {
              item.children.forEach(child => {
                if (rolesList.includes(child.id)) {
                  child.hidden = false;
                }
                // 如果有任一子项的hidden不是true，则allChildrenHiddenTrue为false
                if (child.hidden !== true) {
                  allChildrenHiddenTrue = false;
                }
              });
              // 如果所有子项的hidden都是true，设置item的hidden为true
              if (allChildrenHiddenTrue) {
                item.hidden = true;
              } else {
                item.hidden = false;
              }
            }
          });
        }
        // return
        commit('SET_TOKEN', res.token)
        commit('SET_USERINFO', res)
        setToken(res.token)
        localStorage.setItem('userinfor', JSON.stringify(response));

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(async response => {
        const data = response.rows[0]
        const {rows} = await cusRoleList({ pageNum: 1,pageSize: 10000, platform:''})
        const result = rows.find(item => item.id == data.roles);
        if(result){
          const rolesList = result.menuIds.split(',')
          constantRoutes.forEach(item=>{
            let allChildrenHiddenTrue = true;
            if (item.children && item.children.length > 0) {
              item.children.forEach(child => {
                if (rolesList.includes(child.id)) {
                  child.hidden = false;
                }
                if (child.hidden !== true) {
                  allChildrenHiddenTrue = false;
                }
              });
            }
            if (allChildrenHiddenTrue) {
              item.hidden = true;
            }
          })
          console.log(constantRoutes)
        }
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, headerPic } = data
        commit('SET_USERINFO', data)
        commit('SET_NAME', name)
        commit('SET_AVATAR', headerPic)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

